/**
 * @file Driver_Timer.c
 * @brief 
 * @author 2bam 
 * @version 1.0
 * @date 2024-12-07
 * @copyright Copyright (c) 2024  NULL
 * 
 * @change log:
 * Date           Version Author   Describe
 * 2024-12-07     1.0     2bam     first version
 */

/* Includes -------------------------------------------------------------------*/
#include "tim.h"
#include "Driver_Timer.h"
#include "Driver_Serial.h"
#include "config.h"
#include "rtthread.h"

/* define ---------------------------------------------------------------------*/
#define PWMLED_TIMER    htim2
#define PWMLED_CHANNEL  TIM_CHANNEL_2
/* typedef --------------------------------------------------------------------*/

/* variables ------------------------------------------------------------------*/
struct rt_thread pwm_thread;
static uint8_t pwm_stack[512];
/* Private function prototypes ------------------------------------------------*/


/**
 * @brief 开启定时器
 * @param  htim        My Param doc
 * @date 2024-12-15
 * @author 2bam 
 */
void TimerStart(TIM_HandleTypeDef *htim)
{
    /* Check the TIM handle allocation */
    if (htim == NULL)
    {
        return;
    }
    __HAL_TIM_CLEAR_FLAG(htim,TIM_FLAG_UPDATE);
    HAL_TIM_Base_Start_IT(htim);
}



/**
 * @brief PWM调光
 * @param  htim        My Param doc
 * @param  Channel     My Param doc
 * @date 2024-12-15
 * @author 2bam 
 */
void PWMLEDEntry(void *para)
{
    while (1)
    {
        for(int i=0;i<100;i++)
        {
            __HAL_TIM_SET_COMPARE(&PWMLED_TIMER, PWMLED_CHANNEL,i);
            rt_thread_mdelay(10);
        }

        for(int i=99;i>=0;i--)
        {
            __HAL_TIM_SET_COMPARE(&PWMLED_TIMER, PWMLED_CHANNEL,i);
            rt_thread_mdelay(10);
        }
    }
}
    
/**
 * @brief 将PWM调光设计成线程
 * @return int 
 * @date 2024-12-15
 * @author 2bam 
 */
static int PWMLEDThreadInit(void)
{
    rt_err_t ret;

    /** 开启PWM调光 */
    HAL_TIM_PWM_Start(&PWMLED_TIMER, PWMLED_CHANNEL);

    ret = rt_thread_init(&pwm_thread,
                        "pwmled thread",
                        PWMLEDEntry, NULL,
                        pwm_stack, sizeof(pwm_stack),
                        RT_THREAD_PRIORITY_PWMLED, 20);
    rt_thread_startup(&pwm_thread);
    return ret;
}
INIT_APP_EXPORT(PWMLEDThreadInit);
